<template>
  <section class="app-inner">
    <el-card class="header-card">
      <el-form :inline="true" :model="queryParams" size="small">
        <el-form-item label="角色">
          <el-select
            v-model="queryParams.roleNo"
            placeholder="请选择"
            clearable
            filterable
          >
            <el-option
              v-for="item in roleList"
              :key="item.roleNo"
              :label="item.roleName"
              :value="item.roleNo"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="">
          <el-input
            clearable
            placeholder="请输入姓名"
            v-model="queryParams.userName"
          ></el-input>
        </el-form-item>
        <el-form-item>
          <el-button
            v-if="checkAuthority('/select')"
            type="primary"
            @click="searchQuery"
            style="margin-left: 30px"
            size="small"
            >查询</el-button
          >
          <!-- <el-button type="primary" @click="handleSynchro" size="small"
            >刷新</el-button
          > -->
        </el-form-item>
      </el-form>
    </el-card>

    <el-card class="table-card">
      <section class="table-btn">
        <el-button v-if="checkAuthority('/ucenter/uuser/add')" @click="handleAdd" type="primary" icon="plus" size="small"
          >添加用户</el-button
        >
        <div v-if="checkAuthority('/eyes')" class="switch-btn cursor iconfont" :class="[isShow ? 'icon-yanjing': 'icon-biyan']" @click="handleClickIsShow"></div>
        <!-- <el-button @click="handleDown" type="primary" icon="swap" size="small"
          >下载模板</el-button
        >
        <el-upload
          style="display: inline-block; margin-left: 10px"
          action=""
          :show-file-list="false"
          :http-request="handleUpload"
          :accept="getFiles()"
          size="small"
        >
          <el-button type="primary" icon="import" size="small"
            >批量导入</el-button
          >
        </el-upload> -->
      </section>

      <el-table border :data="tableData" style="width: 100%" row-key="userNo">
        <el-table-column prop="account" label="账号"> </el-table-column>
        <el-table-column prop="userName" label="姓名"> </el-table-column>
        <el-table-column prop="mobile" label="手机号">
          <template v-slot='{row}'>
             <div>{{isShow ?  $options.filters.cellularPhone(row.mobile) : row.mobile}}</div>
          </template>
        </el-table-column>
        <el-table-column prop="employeeNo" label="工号/学籍号">
        </el-table-column>
        <el-table-column label="证件号">
          <template v-slot='{row}'>
             <div>{{isShow && row.idcardNo.length === 18 ?  $options.filters.idCarDesensitization(row.idcardNo) : row.idcardNo}}</div>
          </template>
        </el-table-column>
        <el-table-column prop="userRoleList" label="角色">
          <template slot-scope="scope">
            {{ getRoleListStr(scope.row.userRoleList) }}
          </template>
        </el-table-column>
        <el-table-column prop="isEnable" label="状态" width="80px">
          <template slot-scope="scope">
            <div>{{ getLabel(scope.row.isEnable, 2) }}</div>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="140px">
          <template slot-scope="scope">
            <div>
              <el-button
                v-if="checkAuthority('/ucenter/uuser/passwordReset/')"
                @click.native.prevent="infoReset(scope.row)"
                type="text"
                size="small"
                >重置密码</el-button
              >
              <el-button v-if="checkAuthority('/ucenter/uuser/modify')" type="text" size="small" @click="handleEdit(scope.row)"
                >编辑</el-button
              >
              <el-button
                v-if="checkAuthority('/ucenter/uuser/delete/')"
                type="text"
                size="small"
                @click="handleDelete(scope.row)"
                >删除</el-button
              >
              <el-button
                v-if="checkAuthority('/ucenter/uuser/disableOrEnable/')"
                type="text"
                size="small"
                @click="handleToggle(scope.row)"
                >{{ scope.row.isEnable === 1 ? "禁用" : "启用" }}</el-button
              >
            </div>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        layout="total, prev, pager, next"
        @current-change="pageHandleChange"
        :current-page="currentPage"
        :page-size="pageSize"
        :total="totalPageNum"
      ></el-pagination>
    </el-card>

    <user-modal
      :roleList="roleList"
      ref="userModal"
      @ok="userModalOk"
    ></user-modal>
  </section>
</template>

<script>
import { accountIsEnable, userTypeList, userSourceList } from './js/constants'
import Vue from 'vue'
import { USER_INFO } from '@/store/mutation-types'
import UserModal from './components/UserModal'
import { mapState, mapActions } from 'vuex'
import { decrypt } from '@/utils/crypto'
import {
  getUserList,
  deleteUser,
  downUserTemp,
  importUserFile,
  onOrOffUser,
  passwordReset
} from './js/auth'
import { checkAuthority } from '@/utils/btnPermission' // 页面按钮权限

export default {
  name: 'UserList',
  components: { UserModal },
  data () {
    return {
      currentPage: 1,
      isShow: true,
      pageSize: 10,
      totalPageNum: 0,
      queryParams: {},
      tableData: [],
      userType: Vue.ls.get(USER_INFO).userType,
      userInfo: {
        info: JSON.parse(localStorage.getItem('Standard__User-Info')).value
      }
    }
  },
  created () {
    this.initData()
    this.getAllRoleList()
    this.getAllPositionList()
  },
  computed: {
    ...mapState({
      roleList: (state) => state.auth.roleList
    })
  },
  methods: {
    checkAuthority,
    ...mapActions(['getAllRoleList', 'getAllPositionList']),
    handleClickIsShow () {
      this.isShow = !this.isShow
    },
    // 查询按钮
    searchQuery () {
      this.currentPage = 1
      this.initData()
    },

    // 获取部门列表
    async initData () {
      const params = {
        pageNum: this.currentPage,
        pageSize: this.pageSize
      }
      const {
        code,
        data,
        msg
      } = await getUserList(Object.assign({}, this.queryParams, params))
      let data1 = JSON.parse(decrypt(data))
      if (code === 0) {
        this.tableData = data1.list
        this.totalPageNum = data1.total
      } else {
        this.$message.warning(msg)
      }
    },

    // 用户新增
    handleAdd () {
      this.$refs.userModal.isAdd = true
      this.$refs.userModal.add()
      this.$refs.userModal.title = '新建账号'
    },

    // 用户修改
    handleEdit (row) {
      this.$refs.userModal.isAdd = false
      this.$refs.userModal.edit(row)
      this.$refs.userModal.title = '编辑账号'
    },

    // 删除按钮
    handleDelete (row) {
      this.$confirm('此操作将永久删除该条记录, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          this.dataDelete(row)
        })
        .catch(() => {
          this.$message.warning('已取消删除')
        })
    },
    // 删除函数
    async dataDelete (row) {
      let { tenantNo, userNo, userType } = row

      const { code, msg } = await deleteUser({ tenantNo, userNo, userType })
      if (code === 0) {
        this.$message.success('删除成功')
        if (this.tableData.length === 1 && this.currentPage > 1) {
          this.currentPage--
        }
        this.initData()
      } else {
        this.$message.warning(msg)
      }
    },

    // 启用或禁用
    handleToggle (record) {
      let str = `${record.isEnable === 1 ? '禁用' : '启用'}`
      this.$confirm(`确定${str}该用户吗?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          this.onOrOffUser(record, str)
        })
        .catch(() => {
          this.$message.warning('已取消操作')
        })
    },
    async onOrOffUser (row, str) {
      this.loading = true
      let { tenantNo, userNo, userType } = row
      const { code, msg } = await onOrOffUser({ tenantNo, userNo, userType })
      if (code === 0) {
        this.$message.success(`${str}成功`)
        this.initData()
      } else {
        this.$message.warning(msg)
      }
    },
    // 密码重置
    infoReset (row) {
      this.$confirm('此操作将重置该用户密码 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        await passwordReset(row.userNo)
        this.$message.success('重置成功')
        this.initData()
      })
    },
    // 下载模板
    async handleDown () {
      try {
        const { code } = await downUserTemp()
        if (code === 0) {
          this.$message.success('模板下载成功.xls')
        }
      } catch (e) {
        this.$message.warning(e.msg)
      }
    },

    // 上传限制
    handleUpload (res) {
      let uploadFileObj = res.file
      const isSheet =
        res.file.type === 'application/vnd.ms-excel' ||
        res.file.type ===
        'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
      if (!isSheet) {
        return this.$message.error('上传文件只能是Excel格式!')
      }
      this.fileUploadFun(uploadFileObj)
    },

    // 上传文件
    async fileUploadFun (fileObj) {
      let param = new FormData()
      param.append('file', fileObj)
      const { code, msg } = await importUserFile(param)
      if (code === 0) {
        this.$message.success('批量导入成功')
        this.initData()
      } else {
        this.$message.warning(msg)
      }
    },

    // 用户CU弹框回调
    userModalOk () {
      this.initData()
    },

    // 获取label
    getLabel (val, type) {
      if (type === 1) {
        return this.$base.constFormatter(userSourceList, val)
      }
      if (type === 2) {
        return this.$base.constFormatter(accountIsEnable, val)
      }
    },

    // 页码改变
    pageHandleChange (page) {
      this.currentPage = page
      this.initData()
    },

    // 限制上传的类型
    getFiles () {
      // excel
      let files = [
        'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
        'application/vnd.ms-excel'
      ]
      return files.join(',')
    },

    // format角色
    getRoleListStr (list) {
      return list
        .map((item) => {
          return item.roleName
        })
        .join(' | ')
    },

    getUserTypeStr (str) {
      if (str === '5') {
        return '访客'
      }
      let arr = []
      userTypeList.forEach((item) => {
        if (str.includes(item.value)) {
          arr.push(item.label)
        }
      })
      return arr.join(' | ')
    },

    // 刷新按钮
    handleSynchro () {
      this.$confirm('将手动同步所有用户信息，是否继续执行？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        this.initData()
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.app-inner {
  .table-btn {
    margin-bottom: 15px;
    display: flex;
    justify-content: space-between;
  }
}
.switch-btn{
  width: 50px;
  height: 30px;
  line-height: 30px;
  font-size: 30px;
  text-align: center;
}
</style>
